package com.ysynzehao.db;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * niuzehao
 * 2018/12/7 10:10.
 */
public class DbContextHolder {

    public enum DbType {
        MASTER, SLAVE
    }

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    public static void setDbType(String dbType) {
        if (dbType == null) {
            throw new NullPointerException();
        }
        contextHolder.set(dbType);
    }

    public static String getDbType() {
        return contextHolder.get() == null ? DbType.MASTER.name() : contextHolder.get();
    }

    public static void clearDbType() {
        contextHolder.remove();
    }
}

class DynamicDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return DbContextHolder.getDbType();
    }
}
